/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Jonhnny Weslley
 */
public class RegexBasedParser implements Parser {

	private static final String NO_ID = "no-id";

	private static final Pattern XML_TAG_TEXT = Pattern.compile(".+>(.*)<.+>");
	private static final Pattern USER_ID_NAME = Pattern.compile(".+userid=(.+)\">(.*)</a>.+");

	private static final String MAGIC_1 = "<tr class=\"sectiontableentry1\">";
	private static final String MAGIC_2 = "<tr class=\"sectiontableentry2\">";

	protected final Map<Object, Object> alunos;

	public RegexBasedParser(Map<Object, Object> alunos) {
		this.alunos = alunos;
	}

	@Override
	public List<String[]> parse(Reader source) throws IOException {

		final List<String[]> results = new ArrayList<String[]>();

		BufferedReader reader = new BufferedReader(source); 
		String line = "";
		while ((line = reader.readLine()) != null && alunos.size() > 0) {
			if (line.contains(MAGIC_1) || line.contains(MAGIC_2)) {

				String rank = getInfo(reader.readLine());
				String[] id_name = getUserIdAndName(reader.readLine());

				if (!contains(id_name)) {
					continue;
				}

				String solved = getInfo(reader.readLine());
				String tried = getInfo(reader.readLine());
				String submissions = getInfo(reader.readLine());

				results.add(new String[] {rank, id_name[0], id_name[1], solved, tried, submissions});
				alunos.remove(id_name[0]);
				System.out.println(alunos.size());
			}
		}
		return results;
	}

	protected boolean contains(String[] id_name) {
		return alunos.containsKey(id_name[0]);
	}

	private String getInfo(String line) {
		Matcher matcher = XML_TAG_TEXT.matcher(line);
		matcher.matches();
		return matcher.group(1);
	}

	private String[] getUserIdAndName(String line) {
		try {
			Matcher matcher = USER_ID_NAME.matcher(line);
			matcher.matches();
			return new String[] {matcher.group(1), matcher.group(2)};
		} catch (Exception e) {
			return new String[] {NO_ID, line};
		}
	}

}